package org.xingole.cookbook.helper;

import java.io.File;
import java.io.IOException;

import org.eclipse.jgit.diff.DiffEntry;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.storage.file.FileRepositoryBuilder;

/**
 * The helper utils class for jgit examples.
 */
public class CookbookHelper {
    
    public static Repository openJGitCookbookRepository() throws IOException {
        FileRepositoryBuilder builder = new FileRepositoryBuilder();
        return builder
                .readEnvironment()   // scan environment GIT_* variables
                .findGitDir()        // scan up the file system tree
                .build();
    }

    public static Repository createNewRepository() throws IOException {
        // prepare a new folder
        File localPath = File.createTempFile("TestGitRepository", "");
        // first, delete the existing folder
        if(!localPath.delete()) {
            throw new IOException("Could not delete temporary file" + localPath);
        }

        // create the directory
        Repository repository = FileRepositoryBuilder.create(new File(localPath, ".git"));
        repository.create();

        return repository;
    }

    public static void printDiff(DiffEntry diff) {
        System.out.printf("Diff: %-6s: %s%6s -> %6s: %s%n",
				diff.getChangeType(),
				diff.getDiffAttribute() != null ? diff.getDiffAttribute() + "-" : "",
				diff.getOldMode(), diff.getNewMode(),
				diff.getOldPath().equals(diff.getNewPath()) ? diff.getNewPath() : diff.getOldPath() + " -> " + diff.getNewPath());
    }
}
